import { createRouter, createWebHistory } from "vue-router";

const routes = [
  {
    path: "/",
    redirect: "/index", // 重定向:重新指向其它path,会改变网址
  },
  {
    path: "/login",
    name: "login",
    component: () =>
      import(/* webpackChunkName: "login" */ "../views/Login.vue"),
  },
  {
    path: "/index",
    name: "index",
    component: () =>
      import(/* webpackChunkName: "index" */ "../views/Home.vue"),
    children: [
      {
        path: "home",
        name: "home",
        component: () =>
          import(/* webpackChunkName: "home" */ "../views/HomePage.vue"),
      },
      {
        path: "carnumber",
        name: "carnumber",
        component: () =>
          import(/* webpackChunkName: "carnumber" */ "../views/CarNumber.vue"),
      },
      {
        path: "station",
        name: "station",
        component: () =>
          import(/* webpackChunkName: "station" */ "../views/Station.vue"),
      },
      {
        path: "line",
        name: "line",
        component: () =>
          import(/* webpackChunkName: "line" */ "../views/Line.vue"),
      },
      {
        path: "track",
        name: "track",
        component: () =>
          import(/* webpackChunkName: "track" */ "../views/Track.vue"),
      },
      {
        path: "ticket",
        name: "ticket",
        component: () =>
          import(/* webpackChunkName: "ticket" */ "../views/Ticket.vue"),
      },
      {
        path: "order",
        name: "order",
        component: () =>
          import(/* webpackChunkName: "order" */ "../views/Order.vue"),
      },
      {
        path: "addticket",
        name: "addticket",
        component: () =>
          import(/* webpackChunkName: "addticket" */ "../views/AddTicket.vue"),
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach((to, from, next) => {
  const token = sessionStorage.getItem("token");
  if (to.path === "/login") {
    next();
  }
  if (!token) {
    next({ path: "/login" });
  } else {
    next();
  }
});

export default router;
